import { ajax, toast } from 'nc-lightapp-front';
const prefix = "data:image/png;base64,";
let downloadUrl = 'http://download.piaoeda.com/Releases/projects/servicescan/servicescan_v1.0.0.3.exe';
let scanerUrl = 'https://127.0.0.1:23433'; // http的是23432端口，https的是23433端口
let requestDomain = '';
import $ from './jquery.min' // 因为本地请求使用 axios 时请求 heads 去除 Content-Type 有问题，所以挪用之前逻辑
class HighSpeedPhotoUtil {

    // 文件列表 前拼 data:image/png;base64, 可显示
    scanResultList = [];

    //扫描数据出来的图片数据,未必会用到
    scanResultListShow() {
        return this.scanResultList.map(function (item) {
            return prefix + (item || {}).imgData;
        });
    };

    //判断扫描插件是否安装
    checkScanPlugin = async(callBack, multiLang={}) => {
        const p1 = new Promise(resolve => {
            $.ajax({
                type: 'GET',
                url: scanerUrl + '/checkstatus',
                loading: false,
                contentType: undefined,
                success: (res) => {
                    let code = JSON.parse(res).code;
                    let msg = JSON.parse(res).msg || '';
                    if (code === '0000') {//有本地插件
                        if (msg !== '1.0.0.3') {
                            resolve('update'); // 失败 需要更新最新版本
                        } else {
                            resolve('ok'); // 可以用
                        }
                    } else {
                        resolve('download'); // 失败 需要下载扫描助手
                    }
                },
                error: function () {
                    resolve('error');
                }
            })
        })

        const p2 = new Promise(resolve => {
            setTimeout(() => {
                resolve('pending'); // 工作中
            }, 2500)
        })

        // GlobalStore.showWait();
        let reg = await Promise.race([p1, p2]);
        // GlobalStore.hideWait();

        callBack && callBack(reg);
        if (reg === 'ok') { // 可以用 上层处理

        } else if (reg === 'update') { // 更新版本
            toast({
                duration: 500,
                content: multiLang["high_speed_phone_QGX"] || '', // 请更新扫描助手，完成后重新点击扫描按钮
                TextArr: [multiLang["high_speed_phone_XZZS"] || '', multiLang["high_speed_phone_GB"] || ''], //high_speed_phone_XZZS   high_speed_phone_GB
                onExpand: () => { // 下载
                    window.open(downloadUrl);
                },
                color:"danger"
            });
        } else if (reg === 'download' || reg === 'error') { // 下载或本地安装
            toast({
                duration: 500,
                content: multiLang["high_speed_phone_QGX"] || '', //'请检查本地扫描助手是否运行(如有需要可下载最新版本)，完成后重新点击扫描按钮',
                TextArr: [multiLang["high_speed_phone_XZZS"] || '', multiLang["high_speed_phone_GB"] || ''], //high_speed_phone_XZZS   high_speed_phone_GB
                onExpand: () => { // 下载
                    window.open(downloadUrl);
                },
                color:"danger"
            });
        } else if (reg === 'pending') {
            toast({content: multiLang["high_speed_phone_SMY"] || '', color:'warning'}); // '扫描仪已开启，请确保扫描窗口前置'
        }
    }

    //开始扫描
    startScan = (callBack) => {
        $.ajax({
            type: 'POST',
            url: scanerUrl + '/v1/twain/scan',
            timeout : 1000*60*30, //超时时间设置，单位毫秒 扫描一次30min够用了
            contentType: 'text/plain',
            data: '{"token": "1","bTwainUI": true,"fPixelType": 0,"resolution": 300}',
            success: (res) => {
                var data = JSON.parse(res);
                var code = data.code;
                if (code === '0000') {
                    callBack && callBack(data.datas);
                } else if (code === '0004') {
                    // 选择设备失效。需要重新选择设备
                    this.selectScanDevice(() => {
                        this.startScan(callBack);
                    });
                }
            },
            error: function () {//一般不会走这个逻辑
                toast({content: '扫描失败' ,color: 'danger'});
            }
        });
    }

    //选择设备
    selectScanDevice = (cb) => {
        $.ajax({
            type: 'GET',
            url: scanerUrl + '/v1/twain/select',
            dataType: 'json',
            success: function (data) {
                var code = data.code;
                if (code === '0000') {
                    cb && cb();
                }
            },
            error: function () {
            }
        });
    }

    // 排序
    sortFun = (arr) => {
        let arrNew = JSON.parse(JSON.stringify(arr)).sort((a, b) => {
            // 20200430145804_1588229884948.png
            let aTime = ((a.name || '').split('_')[1] || '').split('.')[0] || '';
            let bTime = ((b.name || '').split('_')[1] || '').split('.')[0] || '';
            return aTime < bTime ? -1 : 1;
        })
        return arrNew;
    }

    // 通过id获取每一张图片base64格式
    getScanResultByIdList = async(idListObj) => {
        let idList = Object.keys(idListObj);
        let promiseList = [];
        let imgList = [];
        if (idList.length) {
            idList.forEach((attr) => {
                const time = new Date()
                let name = this.time(time) + '_' + time.getTime() + '.png';
                promiseList.push(new Promise((resolve) => {
                    $.ajax({
                        type: 'GET',
                        url: scanerUrl + '/v1/twain/image/' + idListObj[attr],
                        contentType: 'text/plain',
                        dataType: 'json',
                        success: (data) => {
                            var code = data.code;
                            if (code === '0000') {//因为这里有异步请求，所以，没办法去统一在complete里执行resolve()
                                let imgData = data.datas.imgData;
                                let item = {
                                    imgData,
                                    name
                                };
                                imgList.push(item);
                                this.scanResultList.push(item);
                                this.scanResultList = this.sortFun(this.scanResultList);
                                resolve();
                            } else {
                                resolve();
                                toast({content: data.msg ,color: 'danger'});
                            }
                        },
                        error() {
                            toast({content: '获取扫描图片异常' ,color: 'danger'});
                            resolve();
                        }
                    });
                }));
            });

            return await new Promise(resolve => {
                Promise.all(promiseList).then(() => {
                    resolve(imgList);
                })
            })
        } else {
            return [];
        }
    }

    // base64 转 file
    dataURLtoFile = (dataurl, filename) => {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type:mime});
    }

    //将base64转换为blob
    dataURLtoBlob = (dataurl) => {
        var arr = dataurl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
    }

    // 上传识别
    uploadFile = (imgList, callBack) => {
        // 注意 file.name 是拍照时的时间戳，file.rename是重命名
        let arr = [];
        let uploadedArr = []; // 上传成功数组

        imgList.forEach(item => {
            arr.push(new Promise((resolve,reject) => {
                // 上传
                ajax({
                    url: `${requestDomain}/nccloud/erm/expenseaccount/ExpenseaccountInvoiceScanAction.do`,
                    data: item,
                    success: (response) => {
                        if(response.data) {
                            uploadedArr.push(response);
                        } else if(response.error) {
                            toast({ content: response.error.message, color: 'danger' })
                        }
                        resolve();
                    },
                    error(err) {
                        if(err.error) {
                            toast({ content: response.error.message, color: 'danger' })
                        }
                        resolve();
                    }
                });
            }))
        })

        Promise.all(arr).then(_ => {
            callBack(uploadedArr);
        })
    }

    // 发票查验
    invoiceVerify = () => {

    }

    time = (time = +new Date()) => {
        // "2018-08-09 18:25:54"
        var date = new Date(time + 8 * 3600 * 1000);
        return date.toJSON().substr(0, 19).replace('T', '').replace(/-|:/g, '');
    }
}

const _highSpeedPhotoUtil = new HighSpeedPhotoUtil()
export default _highSpeedPhotoUtil;
